package com.tiger.contact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * 通讯录助手 tiger 2011-4-29 上午10:37:05
 */
public class MainActivity extends Activity {
	private ContactInfo selectedInfo;
	public TextView contact_num, deal_num;
	private ProgressDialog pd_downloading;
	private final int TO_LOADSIM_CONTACTS = 0x10;
	private final int COPY_CONTACTS = 0x11;
	private final int DELETE_CONTACTS = 0x12;
	private final int BAK_CONTACTS = 0x13;
	private final int RESTORE_CONTACTS = 0x14;
	private Button simContact, phoneContact;
	private ButtonOnClickListener buttonListener;
	private ListView contactList;
	private List<ContactEntity> contactData;
	// private List<ContactEntity> contactDataPhone;
	private ContactAdapter adapter;
	private List<ContactEntity> contactSelected;// 已选择的联系人

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		if (contactSelected != null) {
			contactSelected.clear();
		} else {
			contactSelected = new ArrayList<ContactEntity>();
		}
		pd_downloading = ProgressDialog.show(MainActivity.this, null,
				MainActivity.this.getString(R.string.str_reading_contact),
				true, true);
		this.initView();
		new Thread(new LoadThread()).start();

	}

	private void initView() {
		simContact = (Button) this.findViewById(R.id.simContact);
		phoneContact = (Button) this.findViewById(R.id.phoneContact);
		buttonListener = new ButtonOnClickListener();
		simContact.setOnClickListener(buttonListener);
		phoneContact.setOnClickListener(buttonListener);
		contact_num = (TextView) this.findViewById(R.id.contact_num);
		deal_num = (TextView) this.findViewById(R.id.deal_num);
		adapter = new ContactAdapter(this);
		contactList = (ListView) this.findViewById(R.id.contact_list);
		contactList.setAdapter(adapter);
		contactList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View item,
					int position, long itemId) {
				ContactInfo info = (ContactInfo) item.getTag();
				if (info != null) {
					ContactEntity selectedUser = info.entity;
					if (info.userselect.isChecked()) {
						info.userselect.setChecked(false);
						contactSelected.remove(selectedUser);
					} else {
						info.userselect.setChecked(true);
						contactSelected.add(selectedUser);
					}
					deal_num.setText("已选择" + contactSelected.size() + "个联系人");
				} else {
					Toast.makeText(
							MainActivity.this,
							MainActivity.this
									.getString(R.string.str_item_error),
							Toast.LENGTH_LONG).show();
				}
			}

		});

		contactList.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View item,
					int position, long itemId) {
				// TODO Auto-generated method stub
				ContactInfo info = (ContactInfo) item.getTag();
				selectedInfo = info;
				if (info != null) {
					new AlertDialog.Builder(MainActivity.this).setTitle(
							info.username.getText()).setItems(
							new String[] {
									MainActivity.this
											.getString(R.string.str_to_call),
									MainActivity.this
											.getString(R.string.str_to_sms) },
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									switch (which) {
									case 0:
										String phoneNumber = selectedInfo.phone
												.getText().toString();
										if (phoneNumber != null
												&& phoneNumber.trim() != "") {
											phoneNumber = "tel:" + phoneNumber;
											Intent intent = new Intent(
													Intent.ACTION_CALL, Uri
															.parse(phoneNumber));
											MainActivity.this
													.startActivity(intent);
										} else {
											Intent intent = new Intent(
													Intent.ACTION_DIAL, null);
											MainActivity.this
													.startActivity(intent);
										}
										break;
									case 1:
										Intent it = new Intent(
												Intent.ACTION_VIEW);
										it.putExtra("sms_body", "");
										it.putExtra("address",
												selectedInfo.phone.getText()
														.toString());
										it.setType("vnd.android-dir/mms-sms");
										MainActivity.this.startActivity(it);
										break;
									}
								}
							}).create().show();
				}
				return false;
			}

		});
	}

	class ContactInfo {
		public TextView username;
		public TextView phone;
		public long id;
		public CheckBox userselect;
		public boolean isSelected = false;
		public ContactEntity entity;
	}

	public class ContactAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ContactAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (contactData == null)
				return 0;
			return contactData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ContactInfo holder = null;
			if (convertView == null) {
				holder = new ContactInfo();
				convertView = mInflater.inflate(R.layout.contact_item, null);
				holder.username = (TextView) convertView
						.findViewById(R.id.username);
				holder.phone = (TextView) convertView.findViewById(R.id.phone);
				holder.userselect = (CheckBox) convertView
						.findViewById(R.id.userselect);
			} else {
				holder = (ContactInfo) convertView.getTag();
			}

			if (contactData != null) {
				holder.username.setText(contactData.get(position).getName());
				holder.phone.setText(contactData.get(position).getPhoneNum());
				holder.userselect.setChecked(contactData.get(position).isChecked());
				holder.id = contactData.get(position).getId();
				holder.entity = contactData.get(position);
			}
			convertView.setTag(holder);
			return convertView;
		}

	}

	class ButtonOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			pdhandler.sendEmptyMessage(1);
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.simContact:
				loadType = "sim";
				new Thread(new LoadThread()).start();
				break;
			case R.id.phoneContact:
				loadType = "phone";
				new Thread(new LoadThread()).start();
				break;
			default:

				break;
			}

		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		String msg = "";
		switch (item.getItemId()) {
		case 1:
			if (contactSelected == null || contactSelected.size() == 0) {
				new AlertDialog.Builder(MainActivity.this).setTitle(
						R.string.alert_warn).setMessage(
						R.string.alert_check_contact).setNegativeButton(
						R.string.alert_str_sure,
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).create().show();
				break;
			}
			if (loadType.equals("sim")) {
				msg = this.getString(R.string.str_copy_sim_phone) + "(已选中"
						+ contactSelected.size() + ")";
			} else {
				msg = this.getString(R.string.str_copy_phone_sim) + "(已选中"
						+ contactSelected.size() + ")";
			}
			new AlertDialog.Builder(this)
					.setTitle(this.getString(R.string.str_copy_contact))
					.setMessage(msg)
					.setPositiveButton(
							R.string.alert_str_sure,
							new android.content.DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									pdhandler.sendEmptyMessage(COPY_CONTACTS);
									return;
								}
							})
					.setNegativeButton(
							R.string.alert_str_cancel,
							new android.content.DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									return;
								}
							}).create().show();
			break;
		case 2:
			if (contactSelected == null || contactSelected.size() == 0) {
				new AlertDialog.Builder(MainActivity.this).setTitle(
						R.string.alert_warn).setMessage(
						R.string.alert_check_contact).setNegativeButton(
						R.string.alert_str_sure,
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).create().show();
				break;
			}
			msg = this.getString(R.string.str_delete_msg) + "(已选中"
					+ contactSelected.size() + ")";
			new AlertDialog.Builder(this).setTitle(
					this.getString(R.string.str_deleting_contact)).setMessage(
					msg).setPositiveButton(R.string.alert_str_sure,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							pdhandler.sendEmptyMessage(DELETE_CONTACTS);
							dealContacthandler.sendEmptyMessage(DELETE_CONTACTS);
							return;
						}
					}).setNegativeButton(R.string.alert_str_cancel,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							return;
						}
					}).create().show();
			break;
		case 3:
//			pdhandler.sendEmptyMessage(BAK_CONTACTS);
			pd_downloading = ProgressDialog.show(MainActivity.this, null,
					MainActivity.this
							.getString(R.string.str_baking_contact), true,
					true);
			new Thread(new TestThread()).start();
			break;
		case 4:
			pdhandler.sendEmptyMessage(RESTORE_CONTACTS);
			dealContacthandler.sendEmptyMessage(RESTORE_CONTACTS);
			break;
		case 5:
			confirm(this.getString(R.string.alert_str_exit_msg), this
					.getString(R.string.menu_str_exit));
			break;
		case 6:
			ContactUtil.getInstance().checkAll(this, contactData,
					contactSelected, deal_num, adapter);
			break;
		case 7:
			ContactUtil.getInstance().cancelAll(this, contactData,
					contactSelected, deal_num, adapter);
			break;
		case 8:
			MainActivity.this.startActivity(new Intent(MainActivity.this,
					AddContactActivity.class));
			break;
		case 9:
			AboutUS();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	private class TestThread implements Runnable {
		@Override
		public void run() {
			Looper.prepare();
			dealContacthandler.sendEmptyMessage(BAK_CONTACTS);
			Looper.loop();
		}
	}
	private int dealNum = 0;
	Handler dealContacthandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case COPY_CONTACTS:
				if (loadType.equals("sim")) {
					// dealNum=CommonUtil.deletePhoneContacts(MainActivity.this,
					// contactSelected);
					// CommonUtil.insertPhoneContacts(MainActivity.this,
					// contactSelected);
					loadType = "phone";
				} else {
					// dealNum=CommonUtil.deleteSimContacts(MainActivity.this,
					// contactSelected);
					// CommonUtil.insertSimContacts(MainActivity.this,
					// contactSelected);
					loadType = "sim";
				}
				contact_num.setText("处理" + dealNum + "条");
				pdhandler.sendEmptyMessage(2);
				new Thread(new LoadThread()).start();
				break;
			case DELETE_CONTACTS:
				dealNum = ContactUtil.getInstance().deleteSelectedItems(
						MainActivity.this, contactSelected, loadType);
				deal_num.setText("处理" + dealNum + "条");
				pdhandler.sendEmptyMessage(2);
				new Thread(new LoadThread()).start();
				break;
			case BAK_CONTACTS:
				boolean res=ContactUtil.getInstance().bakContact();
				if(res){
					pdhandler.sendEmptyMessage(2);
//					CommonUtil.dismissDialog(pd_downloading);
				}
				break;
			case RESTORE_CONTACTS:
				res=ContactUtil.getInstance().restoreContact();
				if(res){
					pdhandler.sendEmptyMessage(2);
				}
				break;
			}
		}
	};
	Handler pdhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				pd_downloading = ProgressDialog.show(MainActivity.this, null,
						MainActivity.this
								.getString(R.string.str_reading_contact), true,
						true);
				break;
			case 2:
				if (pd_downloading != null) {
					pd_downloading.dismiss();
					pd_downloading = null;
				}
				if (contactSelected != null) {
					contactSelected.clear();
				} else {
					contactSelected = new ArrayList<ContactEntity>();
				}
				break;
			case COPY_CONTACTS:
				pd_downloading = ProgressDialog.show(MainActivity.this, null,
						MainActivity.this
								.getString(R.string.str_copying_contact), true,
						true);
				dealContacthandler.sendEmptyMessage(COPY_CONTACTS);
				break;
			case DELETE_CONTACTS:
				pd_downloading = ProgressDialog.show(MainActivity.this, null,
						MainActivity.this
								.getString(R.string.str_deleting_contact),
						true, true);
				break;
			case BAK_CONTACTS:
				pd_downloading = ProgressDialog.show(MainActivity.this, null,
						MainActivity.this
								.getString(R.string.str_baking_contact), true,
						true);
				dealContacthandler.sendEmptyMessage(BAK_CONTACTS);
				break;
			case RESTORE_CONTACTS:
				pd_downloading = ProgressDialog.show(MainActivity.this, null,
						MainActivity.this
								.getString(R.string.str_restoring_contact),
						true, true);
				dealContacthandler.sendEmptyMessage(RESTORE_CONTACTS);
				break;
			}
		}
	};
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TO_LOADSIM_CONTACTS:
				if (adapter != null) {
					adapter.notifyDataSetChanged();
					contact_num.setText("读取联系人" + contactData.size() + "个");
				}
				break;
			}
		}
	};
	private String loadType = "sim";

	private class LoadThread implements Runnable {
		@Override
		public void run() {
			Looper.prepare();
			if (loadType.equals("sim")) {
				contactData = ContactUtil.getInstance().loadInfoFromPhone(
						MainActivity.this, "sim");
			} else {
				contactData = ContactUtil.getInstance().loadInfoFromPhone(
						MainActivity.this, "phone");
			}
			pdhandler.sendEmptyMessage(2);
			if (contactData != null && contactData.size() > 0) {
				handler.sendEmptyMessage(TO_LOADSIM_CONTACTS);
			} else {
				Toast
						.makeText(
								MainActivity.this,
								MainActivity.this
										.getString(R.string.str_reading_error),
								Toast.LENGTH_LONG).show();
			}
			Looper.loop();
		}

	};

	public void AboutUS() {
		// 关于
		String about_appname = this.getResources().getString(R.string.app_name);
		String about_ver = this.getResources().getString(R.string.app_ver);
		String about_csmail = this.getResources().getString(
				R.string.about_csmail);
		String about_copyright = this.getResources().getString(
				R.string.about_copyright);
		String app_platform = this.getResources().getString(
				R.string.app_platform);

		CommonUtil.alert(this, about_appname + "(" + app_platform + ")"
				+ "\n版本:" + about_ver + "\n客服邮箱:" + about_csmail + "\n版权信息:"
				+ about_copyright + "", "关于");
	}

	public void confirm(String msg, String title) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg);
		builder.setTitle(title);
		builder.setPositiveButton(R.string.alert_str_sure,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// ActivityManager
						// activityMgr=(ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
						// activityMgr.restartPackage(getPackageName());
						Intent startMain = new Intent(Intent.ACTION_MAIN);
						startMain.addCategory(Intent.CATEGORY_HOME);
						startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(startMain);
						System.exit(0);
					}
				});
		builder.setNegativeButton(R.string.alert_str_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				});
		builder.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			confirm(this.getString(R.string.alert_str_exit_msg), this
					.getString(R.string.menu_str_exit));
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(1, 1, 1, this.getString(R.string.menu_str_copy)).setIcon(
				R.drawable.menu_inputurl);
		menu.add(1, 2, 2, this.getString(R.string.menu_str_del)).setIcon(
				R.drawable.menu_bookmark_sync_sync);
		menu.add(1, 3, 3, this.getString(R.string.menu_str_bak)).setIcon(
				R.drawable.menu_syssettings);
		menu.add(1, 4, 4, this.getString(R.string.menu_str_restore)).setIcon(
				R.drawable.menu_redownload);
		menu.add(1, 5, 5, this.getString(R.string.menu_str_exit)).setIcon(
				R.drawable.menu_quit);
		menu.add(1, 6, 6, this.getString(R.string.menu_str_checkall)).setIcon(
				R.drawable.menu_about);
		menu.add(1, 7, 7, this.getString(R.string.menu_str_cancelall)).setIcon(
				R.drawable.menu_about);
		menu.add(1, 8, 8, this.getString(R.string.menu_str_add)).setIcon(
				R.drawable.menu_about);
		menu.add(1, 9, 9, this.getString(R.string.menu_str_about)).setIcon(
				R.drawable.menu_about);
		return super.onCreateOptionsMenu(menu);
	}
}